import Vue from "vue";
import axios from "axios";
import { ACCESS_TOKEN } from "@/store/constant";
import store from "@/store";

//baseUrl
let apiBaseUrl = window.global_value.VUE_APP_API_URL || "/";
console.log("apiBaseUrl=", apiBaseUrl);

//初始化http类
const request = axios.create({
  baseURL: apiBaseUrl, // 所有的请求地址前缀部分(没有后端请求不用写)
  timeout: 80000, // 请求超时时间(毫秒)
  withCredentials: true, // 异步请求携带cookie
  headers: {
    "X-Requested-With": "XMLHttpRequest",
  },
});

//请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (token) {
      config.headers[ACCESS_TOKEN] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//相应异常处理方法
const err = (error) => {
  if (error.response) {
    let data = error.response.data;
    const token = Vue.ls.get(ACCESS_TOKEN);
    console.log("------异常响应------", token);
    console.log("------异常响应------", error.response.status);
    switch (error.response.status) {
      case 403:
        handleErr(拒绝访问);
        break;
      case 500:
        console.log("------error.response------", error.response);
        if (
          token &&
          (data.message.includes("Token失效") ||
            data.message.includes("Token超时"))
        ) {
          handleErr("很抱歉，登录已过期，请重新登录");
          //执行退出操作
          store.dispatch("user/clearToken");
          window.location.reload();
        }
        break;
      case 404:
        handleErr("很抱歉，资源未找到!");
        break;
      case 504:
        handleErr("网络超时");
        break;
      case 401:
        handleErr("很抱歉，登录已过期，请重新登录");
        break;
      default:
        handleErr(data.message);
        break;
    }
  } else if (error.message) {
    if (error.message.includes("timeout")) {
      handleErr("网络超时");
    } else {
      handleErr(error.message);
    }
  }
  return Promise.reject(error);
};

//展示错误信息方法
const handleErr = (msg) => {
  alert(msg);
};

//响应拦截
request.interceptors.response.use((res) => {
  //返回数据
  const { data } = res;
  console.log("返回数据处理", res);
  return data;
}, err);

export default request;
